<template>
    <div class="app-container">
        <el-row>
            <el-col :span="24">
                <el-card shadow="always" header="退服统计情况" style="margin-bottom: 20px;">
                    <el-table :data="statisticsTableData" v-loading="loading" max-height="500px">
                        <el-table-column prop="exitCounty" label="所属区县" />
                        <el-table-column prop="exitCount" label="退服数量" />
                    </el-table>
                </el-card>
            </el-col>
            <el-col :span="24">
                <el-card shadow="always" header="退服站点列表">
                    <el-form :model="queryParams" :inline="true" label-width="120px">
                        <el-form-item label="所属区县：" prop="county">
                            <el-select v-model="queryParams.county" placeholder="请选择所属区县" clearable
                                style="width: 240px">
                                <el-option v-for="dict in nhp_county_type" :key="dict.value" :label="dict.label"
                                    :value="dict.value" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="网元名称：" prop="neName">
                            <el-input v-model="queryParams.neName" placeholder="请输入网元名称" clearable
                                style="width: 240px" />
                        </el-form-item>
                        <el-form-item label="网络制式：" prop="networkType">
                            <el-select v-model="queryParams.networkType" placeholder="请选择网络制式" clearable
                                style="width: 240px">
                                <el-option v-for="item in networkTypeOptions" :key="item.value" :label="item.key"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" icon="Search" @click="searchData">查询</el-button>
                            <el-button @click="unsetQueryForm"><el-icon>
                                    <RefreshRight />
                                </el-icon>重置</el-button>
                            <!-- <el-button type="primary" icon="Download" @click="exportData">导出</el-button> -->
                            <!-- <el-button type="primary" icon="Tools" @click="showConfigDialog">配置</el-button> -->
                        </el-form-item>
                    </el-form>
                    <el-row style="margin-bottom: 10px;">
                        <el-button type="primary" icon="Upload" @click="importFile">导入</el-button>
                        <el-button type="primary" icon="Download" @click="exportData">导出</el-button>
                        <el-button type="primary" icon="Download" @click="exportData1">导出自定义数据</el-button>
                        <el-button type="primary" icon="Download" @click="exportData2" :disabled="true"
                            title="正在开发中">导出已恢复数据</el-button>
                    </el-row>
                    <!-- <el-table :data="exitTableData" style="width: 100%" @sort-change="sortChange"> -->
                    <el-table :data="exitTableData" style="width: 100%" v-loading="loading">
                        <el-table-column fixed prop="county" label="区县" width="100" align="center" />
                        <el-table-column prop="neName" label="网元名称" width="280" align="center" show-overflow-tooltip />
                        <el-table-column prop="siteId" label="站号" width="90" align="center" />
                        <el-table-column prop="alarmTitles" label="告警标题" width="180" align="center" />
                        <!-- <el-table-column prop="exitCause" label="退服成因" min-width="320" /> -->
                        <el-table-column prop="eventTime" label="告警首次发生时间" :formatter="dateFormatter" width="250"
                            align="center" sortable />
                        <el-table-column prop="level" label="基站分级" width="100" align="center" />
                        <!-- <el-table-column label="基站分级" width="150" align="center">
                            <template #default="scope">
                                <span v-if="scope.row.networkType === '4G'">{{ scope.row.vipLevel }}</span>
                                <span v-else>{{ scope.row.stationLevel }}</span>
                            </template>
</el-table-column> -->
                        <el-table-column label="长时退服" width="89" align="center">
                            <template #default="scope">
                                <el-tag type="warning" v-if=isLongText(scope.row.eventTime)>长时</el-tag>
                                <span v-else>-</span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="networkType" label="网络制式" width="150" align="center" />
                        <!-- sortable="custom" -->

                        <el-table-column prop="exitCause" label="退服成因" min-width="320">
                            <template #default="scope">
                                {{ scope.row.exitCause ? scope.row.exitCause : '-' }}
                            </template>
                        </el-table-column>
                        <el-table-column prop="eventTime" sortable label="持续时间" width="100" :formatter="endureFormatter"
                            align="center" />
                        <el-table-column fixed="right" label="操作" align="center">
                            <template #default="scope">
                                <el-button link type="primary" size="small"
                                    @click="showDetailDialog(scope.row)">退服成因</el-button>
                                <!-- <el-button link type="primary" size="small" @click="showDetailDialog(scope.row)"
                                    :disabled="scope.row.exitCause">退服成因</el-button> -->
                            </template>
                        </el-table-column>
                    </el-table>
                    <pagination v-show="total > 0" :total="total" v-model:page="currentPage" v-model:limit="pageSize"
                        @pagination="listExitSiteInfoData" :autoScroll="false" />
                </el-card>
            </el-col>
        </el-row>

        <exitDialog ref="refExitDialog" @reflash="listExitSiteInfoData" />

        <el-dialog v-model="importDialogVisible" title="导入文件" width="400">
            <el-form label-width="120px">
                <el-form-item label="文件上传">
                    <el-upload :action="uploadFileUrl" class="upload-demo" :headers="headers">
                        <el-button type="primary">上传</el-button>
                    </el-upload>
                </el-form-item>
                <el-form-item label="模版下载">
                    <a @click="downloadTemplate" class="download-link">退服清单.xlsx</a>
                </el-form-item>
            </el-form>
        </el-dialog>

        <export-dialog ref="refExportDialog" @directExport="directExportData" />
    </div>
</template>

<script setup>
const { proxy } = getCurrentInstance();
import { getToken } from '@/utils/auth'
import { queryExitSiteInfoList, queryExitSiteInfoList1, queryExitSiteStatistics } from '@/api/biz/maintenance';
import { useConfigStore } from '@/store/modules/config.js'
import exitDialog from './exitDialog.vue';

const { nhp_county_type } = proxy.useDict("nhp_county_type");

const queryParams = ref({})
const refExitDialog = ref(null)
const importDialogVisible = ref(false)
const exitTableData = ref([])
const statisticsTableData = ref([])
const networkTypeOptions = [
    {
        key: "4G",
        value: "103"
    },
    {
        key: "5G",
        value: "108"
    },
    {
        key: "2G",
        value: "101"
    }
]

const currentPage = ref(1)
const refExportDialog = ref(null)
const pageSize = ref(10)
const total = ref(0)
const nowSortContent = ref();
const nowOrder = ref();
const configStoreData = useConfigStore()
let securityFlagConfig = configStoreData.configList.filter(item => item.configKey === 'sys.securityFlag')[0]

const uploadFileUrl = ref(import.meta.env.VITE_APP_BASE_API + "/maintenance/exitImport"); // 上传文件服务器地址
const headers = ref({ Authorization: "Bearer " + getToken() });

let loading = ref(false)

const searchData = () => {
    listExitSiteInfoData()
    getStatisticsTableData()
}

const getStatisticsTableData = () => {
    loading.value = true
    queryExitSiteStatistics().then(res => {
        loading.value = false
        statisticsTableData.value = res.data
    })
}
getStatisticsTableData()

function sortChange(column, prop, order) {
    nowOrder.value = column.order;
    nowSortContent.value = column.prop;
    listExitSiteInfoData1();
}

const unsetQueryForm = () => {
    queryParams.value = {
    }
    searchData()()
}

const showDetailDialog = (row) => {
    refExitDialog.value.show(row)
}

function importFile() {
    importDialogVisible.value = true
}

function listExitSiteInfoData() {
    loading.value = true
    const param = {}
    param.pageSize = pageSize.value;
    param.pageNum = currentPage.value;
    param.county = queryParams.value.county
    param.neName = queryParams.value.neName
    param.networkType = queryParams.value.networkType
    param.order = nowOrder.value;
    param.sortContent = nowSortContent.value;

    queryExitSiteInfoList(param).then(res => {
        loading.value = false
        total.value = res.total
        exitTableData.value = res.rows

        exitTableData.value.forEach(item => {
            networkTypeOptions.forEach(networkType => {
                if (networkType.value == item.networkType) {
                    item.networkType = networkType.key
                }
            })
        })
    })
}
function listExitSiteInfoData1() {
    const param = {}
    param.pageSize = pageSize.value;
    param.pageNum = currentPage.value;
    param.county = queryParams.value.county
    param.neName = queryParams.value.neName
    param.networkType = queryParams.value.networkType
    param.order = nowOrder.value;
    param.sortContent = nowSortContent.value;

    queryExitSiteInfoList1(param).then(res => {
        total.value = res.total
        exitTableData.value = res.rows
    })
}

function networkTypeFormatter(row, column, cellValue, index) {
    if (!cellValue) { return }
    if (cellValue == '103') {
        return '4G';
    } else if (cellValue == '108') {
        return '5G';
    } else if (cellValue == '101') {
        return '2G';
    }
}

function dateFormatter(row, column, cellValue, index) {
    if (!cellValue) { return }
    // 创建一个新的 Date 对象
    var originalDate = new Date(cellValue);

    // 获取年、月、日、时、分、秒
    var year = originalDate.getFullYear();
    var month = ("0" + (originalDate.getMonth() + 1)).slice(-2);
    var day = ("0" + originalDate.getDate()).slice(-2);
    var hours = ("0" + originalDate.getHours()).slice(-2);
    var minutes = ("0" + originalDate.getMinutes()).slice(-2);
    var seconds = ("0" + originalDate.getSeconds()).slice(-2);

    // 格式化输出
    var formattedDateTimeString = year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;
    return formattedDateTimeString;
}

function endureFormatter(row, column, cellValue, index) {
    if (!cellValue) { return }
    var originalDate = new Date(cellValue);
    //计算originalDate距离当前的时间的小时数
    // 获取当前时间
    var currentDate = new Date();
    // 计算时间差（毫秒）
    var timeDifference = currentDate - originalDate;
    // 将毫秒转换为小时（1小时 = 3600000毫秒）
    // 保留两位小数
    var hoursDifference = timeDifference / (1000 * 3600);
    hoursDifference = hoursDifference.toFixed(2);
    return hoursDifference;
}

const isLongText = (cellValue) => {
    if (!cellValue) { return }
    var originalDate = new Date(cellValue);
    //计算originalDate距离当前的时间的小时数
    // 获取当前时间
    var currentDate = new Date();
    // 计算时间差（毫秒）
    var timeDifference = currentDate - originalDate;
    // 将毫秒转换为小时（1小时 = 3600000毫秒）
    // 保留两位小数
    var hoursDifference = timeDifference / (1000 * 3600);
    hoursDifference = hoursDifference.toFixed(2);
    return parseInt(hoursDifference) > 24;
}

// 导出明面上的数据
function exportData() {
    const param = {}
    param.pageSize = pageSize.value;
    param.pageNum = currentPage.value;
    param.county = queryParams.value.county
    param.neName = queryParams.value.neName
    param.networkType = queryParams.value.networkType
    param.order = nowOrder.value;
    param.sortContent = nowSortContent.value;
    //首先判断金库模式开关是否开启
    if (securityFlagConfig.configValue == "true") {
        // refExportDialog.value.show(param)
    } else {
        //未开启
        proxy.download("/maintenance/exportExitSiteInfoList", {
            ...param
        }, `无线退服管理_${new Date().getTime()}.xlsx`);
    }
}

// 导出用户上传的退服清单
const exportData1 = () => {
    const param = {}
    proxy.download("/maintenance/queryExitOutputInfoList", {
        ...param
    }, `无线退服管理_${new Date().getTime()}.xlsx`);
}

// 导出无线退服管理_已恢复数据
const exportData2 = () => {
    const param = {}
    proxy.download("/maintenance/exportRecoveredList", {
        ...param
    }, `无线退服管理_已恢复数据_${new Date().getTime()}.xlsx`);
}

function directExportData() {
    const param = {}
    param.pageSize = pageSize.value;
    param.pageNum = currentPage.value;
    param.county = queryParams.value.county
    param.neName = queryParams.value.neName
    param.networkType = queryParams.value.networkType
    param.order = nowOrder.value;
    param.sortContent = nowSortContent.value;

    /* proxy.download("/maintenance/exportExitSiteInfoList", {
        ...param
    }, `无线退服管理_${new Date().getTime()}.xlsx`); */
}

function downloadTemplate() {
    proxy.download("/export/downloadTemplate", {
        templateName: "无线退服管理.xlsx"
    }, `退服清单.xlsx`);
}

listExitSiteInfoData()

</script>